#!/bin/bash


# -------------------------------------------------------------------------------
# Filename:    pxe.sh
# Revision:    1.2
# Date:        2019/11/6
# Author:      xianfengya
# Email:       live#xianfengya.cn
# Description: This is a script to deploy PXE servers.
# -------------------------------------------------------------------------------


#挂载镜像，生成yum源文件
mkdir /mnt/cdrom
mount /dev/sr0 /mnt/cdrom
mkdir /etc/yum.repos.d/bak
mv /etc/yum.repos.d/rhel* /etc/yum.repos.d/bak
mv /etc/yum.repos.d/CentOS* /etc/yum.repos.d/bak
#配置yum本地源
cat << EOF > /etc/yum.repos.d/cdrom.repo
[CDROM]
name=cdrom
baseurl=file:///mnt/cdrom
gpgcheck=0
enabled=1
cost=100
EOF

#清除yum缓存
yum clean all

#生成缓存加速安装
yum makecache

#安装需要的程序
yum -y install dhcp tftp-server xinetd syslinux httpd

#配置dhcp服务
cat << EOF > /etc/dhcp/dhcpd.conf
allow booting;
allow bootp;
ddns-update-style interim;
ignore client-updates;
subnet 192.168.10.0 netmask 255.255.255.0 {
option subnet-mask 255.255.255.0;
option domain-name-servers 192.168.10.10;
range dynamic-bootp 192.168.10.100 192.168.10.200;
default-lease-time 21600;
max-lease-time 43200;
next-server 192.168.10.10;
filename "pxelinux.0";
}
EOF
#重启dhcp服务
systemctl restart dhcpd
#将dhcp服务加入到开机启动
systemctl enable dhcpd


#设置tftp服务
sed -i '/\<disable\>/s/\<yes\>/no/' /etc/xinetd.d/tftp
#重启xinetd
systemctl restart xinetd
#xinetd加入开启启动服务
systemctl enable xinetd

#停止firewall
systemctl stop firewalld.service
#禁止firewall开机启动
systemctl disable firewalld.service

#配置TFtp下的引导
cd /var/lib/tftpboot
cp /usr/share/syslinux/pxelinux.0 /var/lib/tftpboot
cp /mnt/cdrom/images/pxeboot/{vmlinuz,initrd.img} /var/lib/tftpboot
cp /mnt/cdrom/isolinux/{vesamenu.c32,boot.msg} /var/lib/tftpboot

#创建pxelinux.cfg文明夹
mkdir /var/lib/tftpboot/pxelinux.cfg
#复制文件
cp /mnt/cdrom/isolinux/isolinux.cfg /var/lib/tftpboot/pxelinux.cfg/default



#在html下创建cdrom文件夹
mkdir /var/www/html/cdrom
#将虚拟机下挂载的镜像在挂载到/var/www/html/cdrom
mount /dev/sr0 /var/www/html/cdrom

#复制ks文件到/var/www/html下
cp ~/anaconda-ks.cfg /var/www/html/ks.cfg
#将ks文件归属为Apache，这样就有权限使用这文件
chown apache:apache /var/www/html/ks.cfg

#重启httpd服务
systemctl restart httpd
#开机启动httpd服务
systemctl enable httpd

#修改ks文件和default
sed -i 's/default vesamenu.c32/default linux/g' /var/lib/tftpboot/pxelinux.cfg/default
sed -i '64iappend initrd=initrd.img inst.repo=http://192.168.10.10/cdrom ks=http://192.168.10.10/ks.cfg' /var/lib/tftpboot/pxelinux.cfg/default
sed -i '65d' /var/lib/tftpboot/pxelinux.cfg/default



echo '脚本执行完成,请修改/var/www/html/ks.cfg文件，开始你的安装之旅'
echo 'url --url=http://192.168.10.10/cdrom'